<?php
    class System {
        
        private $user_id;
        private $role;
        private $ci;
        private $config;       
        private $allowed = array(); 
        
        function __construct() {
            $this->ci = &get_instance();
            $this->ci->load->library('auth');
            $this->user_id = 0;
            $this->role = array();
            //Config load
            $config = $this->ci->db->get('config')->result_array();
            foreach($config as $conf) {
                $this->config[strtoupper($conf['config_name'])] = $conf['config_value'];
            }
            
            //User session load or init guest session            
            if($this->ci->auth->login_from_session()) {
                $this->user_id = $this->ci->session->userdata('pos_user_id');                
            } else {
                $this->user_id = 0;
            }
                        
            
            if(!$this->isGuest()) { 
                $user = $this->ci->db->select(array('id', 'username', 'email', 'role_id'))
                    ->where('id', $this->getUserId())
                    ->get('users')->row_array();
                if(!empty($user)) {
                    $this->role = $this->ci->db->where('id', $user['role_id'])->get('roles')->row_array();                    
                }                
            } else {
                $this->role = $this->ci->db->where('rolename', 'guest')->get('roles')->row_array();
            }
            
            //var_dump($this->allowed);                                        
        }                
        
        function getUserId() {
            return $this->user_id;
        }
        
        function getRole($index = FALSE) {
            if($index == FALSE) {
                return $this->role;
            }
            
            return isset($this->role[$index]) ? $this->role[$index] : FALSE;
        }
        
        function getConfig() {
            return $this->config;
        }
        
        function isGuest() {
            return (intval($this->user_id) === 0);
        }
        
        function allow($index) {
            $this->allowed[] = $index;
        }
        
        function isAllowed($index) {
            return in_array($index, $this->allowed);
        }                
    }
    
    $CI = &get_instance();
    $CI->load->file(APPPATH . 'libraries/Registry'.EXT);
?>